package Server.GUI;

import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.util.*; 
import javax.swing.JTable;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
 
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author TIN
 */
public class NhapLieu extends javax.swing.JFrame {

    /**
     * Creates new form NhapLieu
     */
    
   int k=0;// nhan biet lan dau chay luc do tfduongdan.setText() chua co j ta se load file a.xml mac dinh
    TableModel dataModel = new DefaultTableModel(loadRowData(),loadColumnName());
    int socot;
    String  Column[];
    String  Column2[];
    String  Column3[];
    String  Column4[];
    public NhapLieu() {
        initComponents();
    tfduongdan.setText("Day la du lieu file mac dinh a.xml,ban hay chon file!!");
       k=1;// Nhan biet khi tfduongdan.setText() da duoc nguoi dung chon
      jTable2.setModel(dataModel);
      int h=  jTable2.getSelectedRow();
              //dataModel.getRowCount();
      String m= Integer.toString(h);
     // tfduongdan.setText(m);
     // if (dataModel == null )
   // tfduongdan.setText(m);
    }
    
         private static String getTagValue(String sTag, Element eElement) {
	NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
 
        Node nValue = (Node) nlList.item(0);
 
	return nValue.getNodeValue();
        
    }
    
    private void loadTable(){
       // TableModel dataModel = new DefaultTableModel(loadRowData(),loadColumnName());
      jTable2.setModel(dataModel);
    // tfduongdan.setText( dataModel.getValueAt( 0, 0).toString());
    }
    private Object[] loadColumnName(){
        
        
         String mang[];
         String mang2[];
         String mang3[];
         String mang4[];
         
         
         
       mang = new String[10];
       mang2 = new String[10];
       mang3 = new String[10];
       mang4 = new String[10];
        
                      for(int i=0;i<10;i++)
                {
                    mang[i] = "";
                    mang2[i] = "";
                    mang3[i] = "";
                    mang4[i] = "";
                    

                }
                      
       
                     //String dulieu= tfduongdan.getText();
                      int temp = 0;
        try {
             File  fXmlFile = new File("a.xml");
                 if (k==1)
                 {
                 //  tfduongdan.setText("thua");
                fXmlFile = new File(tfduongdan.getText().toString());
                }
               
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
 
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("Column");
		System.out.println("-----------------------");
                 int dong=0;
                // NodeList childNode = root.getChildNodes();
                 
		for (temp=0; temp < nList.getLength(); temp++) {
                       
		   Node nNode = nList.item(temp);
		   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
		   //   Element eElement = (Element) nNode;
                            // tfduongdan.setText();
                      Element eElement = (Element) nList.item(temp);
                     //  if (getTagValue("TinhTrang", eElement).compareTo("CON")==0)
                        //  temp++;
                       {
                          socot = temp;
		      //System.out.println(getTagValue("MSSV", eElement));
                      mang[temp]=eElement.getAttribute("name");
                      mang2[temp]=eElement.getAttribute("null");
                      mang3[temp]=eElement.getAttribute("primary");
                      mang4[temp]=eElement.getAttribute("type");
		    // System.out.println("name : " + getTagValue("name", eElement));
                     // mang[dong][1]= getTagValue("Ten", eElement);
	             // System.out.println("NgaySinh : " + getTagValue("NgaySinh", eElement));
                     //  mang[dong][2]= getTagValue("NgaySinh", eElement);
		      //System.out.println("GioiTinh : " + getTagValue("GioiTinh", eElement));
                     //  mang[dong][3]= getTagValue("GioiTinh", eElement);
                       //dong++;
                       }                          
		   }
		}
 
                
	  } catch (Exception e) {
		e.printStackTrace(); 
     }
      Column= new String[temp];
      Column2= new String[temp];
      Column3= new String[temp];
      Column4= new String[temp];
       for( int i=0;i<temp;i++)
       {
       Column[i]= mang[i];
       Column2[i]= mang2[i];
       Column3[i]= mang3[i];
       Column4[i]= mang4[i];   
       }
       return Column;
        
        
        
        //return new Object[]{mang[0],mang[2],"NgaySinh","GioiTinh"};
    }
    private Object[][] loadRowData(){
         //Object h[][] = new String [4][4];
        String mang[][];
       mang = new String[10][10];
                      for(int i=0;i<10;i++)
                {
                    mang[i][0] = "";
                    mang[i][1] = "";
                    mang[i][2] = "";
                    mang[i][3] = "";
                }
                     //String dulieu= tfduongdan.getText();
        try {
             File  fXmlFile = new File("a.xml");
                 if (k==1)
                {
                 //   tfduongdan.setText("thua");
                 fXmlFile = new File(tfduongdan.getText().toString());
                 }
               
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
 
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("row");
		System.out.println("-----------------------");
                 int cot=0;

                 NodeList nList2 = doc.getElementsByTagName("Column");
                 socot = nList2.getLength();
		for (int temp = 0; temp < nList.getLength(); temp++) 
                    // for( int j =0;j< 2;j++)  
                     {
		   Node nNode = nList.item(temp);
		   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
		     // Element eElement = (Element) nNode;
                         Element eElement = (Element) nList.item(temp);
                            // tfduongdan.setText();
                      
                     //  if (getTagValue("TinhTrang", eElement).compareTo("CON")==0)
                        //  temp++;
                       {
                       int sodong1cot= nList.getLength()/socot;
                          int j = temp/sodong1cot;
                          int i = temp%sodong1cot;
		      //System.out.println(getTagValue("MSSV", eElement));
                     // mang[0][dong]= getTagValue("id", eElement);
		     // System.out.println("Ten : " + getTagValue("Ten", eElement));
                      mang[i][j]= eElement.getAttribute("text");
                      //mang[0][1]= eElement.getAttribute("dulieu");
	             // System.out.println("NgaySinh : " + getTagValue("NgaySinh", eElement));
                    //   mang[dong][2]= getTagValue("NgaySinh", eElement);
		      //System.out.println("GioiTinh : " + getTagValue("GioiTinh", eElement));
                    //   mang[dong][3]= getTagValue("GioiTinh", eElement);
                       cot++;
                       }                          
		   }
		}
 
                
	  } catch (Exception e) {
		e.printStackTrace(); 
     }
               
        return mang;
    }
    
    
 
    public  void ghi()
    {
 
	  try {
 
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		// root elements
		Document doc = docBuilder.newDocument();
               // int dong =0;
                Element rootElement = doc.createElement("Table");
      
		doc.appendChild(rootElement);		
                
                for (int j = 0;j<=socot;j++)
                {
                Element staff = doc.createElement("Column");
                Attr attr = doc.createAttribute("name");
		attr.setValue(Column[j]);
		staff.setAttributeNode(attr);
                
                attr = doc.createAttribute("null");
		attr.setValue(Column2[j]);
		staff.setAttributeNode(attr);
                
                attr = doc.createAttribute("primary");
		attr.setValue(Column3[j]);
		staff.setAttributeNode(attr);
                
                attr = doc.createAttribute("type");
		attr.setValue(Column4[j]);
		staff.setAttributeNode(attr);
                
		rootElement.appendChild(staff);
                
                
                for(int dong=0;dong<10;dong++)
                {
                if(dataModel.getValueAt( dong,0).toString()!="")
                

                {
                 
		// staff elements

                 
		// set attribute to staff element
		//Attr attr = doc.createAttribute("id");
		//attr.setValue("1");
		//staff.setAttributeNode(attr);
 
		// shorten way
		// staff.setAttribute("id", "1");
 
		// firstname elements
                Element firstname = doc.createElement("row");
		//firstname.appendChild(doc.createTextNode("CON"));
		
               
         
         
                Attr att2 = doc.createAttribute("text");
		att2.setValue(dataModel.getValueAt( dong, j).toString());
		firstname.setAttributeNode(att2);
               
                
               Attr att = doc.createAttribute("id");
		att.setValue("1");
		firstname.setAttributeNode(att);
                staff.appendChild(firstname);
                }
                
		// lastname elements
	/*	Element lastname = doc.createElement("MSSV");
              //tfduongdan.setText( dataModel.getValueAt( 1, 1).toString());
		lastname.appendChild(doc.createTextNode(dataModel.getValueAt( dong, 0).toString()));
		staff.appendChild(lastname);
 
		// nickname elements
		Element nickname = doc.createElement("Ten");
		nickname.appendChild(doc.createTextNode(dataModel.getValueAt( dong, 1).toString()));
		staff.appendChild(nickname);
 
		// salary elements
		Element salary = doc.createElement("NgaySinh");
		salary.appendChild(doc.createTextNode(dataModel.getValueAt( dong, 2).toString()));
		staff.appendChild(salary);
                
                Element sa = doc.createElement("GioiTinh");
		sa.appendChild(doc.createTextNode(dataModel.getValueAt( dong, 3).toString()));
		staff.appendChild(sa);
                */
                //dong++;
                }
                }
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
                
                // File  fXmlFile = new File("a.xml");
                StreamResult result;
                 if (tfduongdan.getText().compareTo("Day la du lieu file mac dinh a.xml,ban hay chon file!!")!=0)
                 result = new StreamResult(tfduongdan.getText().toString());                
                 else 
                    result = new StreamResult("a.xml");
                
		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);
 
		transformer.transform(source, result);
                
		System.out.println("File saved!");
 
	  } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	  } catch (TransformerException tfe) {
		tfe.printStackTrace();
	  }
    }
    
    
    
    
  /*     public  static void ghi()
    {
       
           //TableModel dataModel = new DefaultTableModel(loadRowData(),loadColumnName());
           // jTable2.setModel(dataModel);
	  try {
 
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("Truong");
		doc.appendChild(rootElement);
 
		// staff elements
                int length=0;
               
               // while((dataModel.getValueAt( length, 1).toString())!=null )
                {
		Element staff = doc.createElement("HocSinh");
		rootElement.appendChild(staff);
                length ++;
		// set attribute to staff element
		//Attr attr = doc.createAttribute("id");
		//attr.setValue("1");
		//staff.setAttributeNode(attr);
 
		// shorten way
		// staff.setAttribute("id", "1");
 
		// firstname elements
		Element firstname = doc.createElement("TinhTrang");
		firstname.appendChild(doc.createTextNode("CON"));
		staff.appendChild(firstname);
 
		// lastname elements
		Element lastname = doc.createElement("MSSV");
		lastname.appendChild(doc.createTextNode(dataModel.getValueAt( length, 1).toString()));
		staff.appendChild(lastname);
 
		// nickname elements
		Element nickname = doc.createElement("HoTen");
		nickname.appendChild(doc.createTextNode(dataModel.getValueAt( length, 2).toString()));
		staff.appendChild(nickname);
 
		// salary elements
		Element salary = doc.createElement("NgaySinh");
		salary.appendChild(doc.createTextNode(dataModel.getValueAt( length, 2).toString()));
		staff.appendChild(salary);
                
                Element sala = doc.createElement("GioiTinh");
		sala.appendChild(doc.createTextNode(dataModel.getValueAt( length, 3).toString()));
		staff.appendChild(salary);
 
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File("C:\\file.xml"));
 
		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);
 
		transformer.transform(source, result);
 
		System.out.println("File saved!");
 
	  } 
//catch (ParserConfigurationException pce) {
		//pce.printStackTrace();
	  } catch (TransformerException tfe) {
		tfe.printStackTrace();
	  
	   }
   // }
    }
    */
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        tfduongdan = new javax.swing.JTextField();
        bbduogndan = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"a", "aa", "a", null, null},
                {null, "a", null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "HoTen", "MSSV", "Ngaysinh", "GioiTinh", "NoiSinh"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        tfduongdan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfduongdanActionPerformed(evt);
            }
        });

        bbduogndan.setText(".........");
        bbduogndan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bbduogndanActionPerformed(evt);
            }
        });

        jButton1.setText("Cancel");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Save");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("InputPath: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(115, 115, 115)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(110, 110, 110)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(tfduongdan)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bbduogndan)
                                .addGap(36, 36, 36))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfduongdan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bbduogndan))
                .addGap(24, 24, 24)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfduongdanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfduongdanActionPerformed
        // TODO add your handling code here:

   }//GEN-LAST:event_tfduongdanActionPerformed

    private void bbduogndanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bbduogndanActionPerformed
        // TODO add your handling code here:
        //JFileChooser fc = new JFileChooser();
      // fc.showOpenDialog(this);
       // tfduongdan.setText(fc.getSelectedFile().toString());
        //doc();
        
    JFileChooser fc = new JFileChooser();  
    fc.showOpenDialog(this);  
    
    tfduongdan.setText(fc.getSelectedFile().toString()); 
    dataModel = new DefaultTableModel(loadRowData(),loadColumnName());
     loadTable();
    }//GEN-LAST:event_bbduogndanActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // Ham nay bao gom ca them va sua
        ghi();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NhapLieu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NhapLieu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NhapLieu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NhapLieu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
            
       
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NhapLieu().setVisible(true);
            }
        });
        
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bbduogndan;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField tfduongdan;
    // End of variables declaration//GEN-END:variables
}
